from flask import Flask,request,session,render_template
from sqlalchemy import and_

from application.schedule import schedule
from db_util.models import db,Schedule,Colleague
import json



#跳转到待办界面
@schedule.route("/schedule/toScheduleList",methods=['GET','POST'])
def toScheduleList():
    return render_template("user/user_todolist.html")
#######################################
#   定义接口：日程模块（待办模块）
#   因为日程和待办相差不多，考虑用一个
#   模块一张表来管理。
#   当repeat为0的时候，为待办。
#   当repeat为1的时候，为日程。
#######################################
#待办列表
@schedule.route("/schedule/schedule_list",methods=['GET','POST'])
def schedule_list():
    user_id = session["user_id"]
    schedule_list = db.session.query(Schedule).filter((Schedule.user_id==user_id)).all()

    res = "["
    i = 0;
    for item in schedule_list:
        if i != 0:
            res = res + ","
        if item.finished == 0:
            item_str = "{\"start\":\"" + item.start_time.strftime(
                "%Y-%m-%d %H:%S:%M") + "\",\"end\":\"" + item.end_time.strftime(
                "%Y-%m-%d %H:%S:%M") + "\",\"title\":\"" + item.title + "\",\"id\":\""+str(item.id)+"\",\"color\":\"red\"}";
        else :
            item_str = "{\"start\":\"" + item.start_time.strftime(
                "%Y-%m-%d %H:%S:%M") + "\",\"end\":\"" + item.end_time.strftime(
                "%Y-%m-%d %H:%S:%M") + "\",\"title\":\"" + item.title + "\",\"id\":\"" + str(item.id) + "\",\"color\":\"blue\"}";
        i=i+1
        res = res + item_str;
        print(i);
    res = res + "]"
    schedule_list = json.dumps(res)
    db.session.close();
    return schedule_list

#待办新增
@schedule.route("/schedule/schedule_add",methods=['GET','POST'])
def schedule_add():
    if login_judge() == False:
        return("尚未登陆")
    schedule = Schedule()
    data = request.get_data("data")
    data = bytes.decode(data);

    if (len(data) > 0):
        data = json.loads(data)
    print(data);
    schedule.title =  data['title']
    schedule.start_time = data['sdate']
    schedule.end_time = data['edate']
    schedule.user_id = session["user_id"]
    schedule.finished = 0;
    print("#############"+session['colleague_id']+" = "+session['user_id']);
    if ((session['colleague_id']!='') & (session['user_id'] != session['colleague_id'])):
        colleague = db.session.query(Colleague).filter(
            and_(Colleague.user_id == session['colleague_id'], Colleague.colleague_id == session['user_id'])).first();
        if (colleague.permission == 0):
            return ("无权限操作！");
        else:
            schedule.user_id = session['colleague_id'];
    db.session.add(schedule)
    db.session.commit()
    db.session.close();
    return("新增待办成功！")

#待办完成
@schedule.route("/schedule/schedule_finish",methods=['GET','POST'])
def schedule_finish():
    if login_judge() == False:
        return ("尚未登陆")
    data = request.get_data("data")
    data = bytes.decode(data);

    if (len(data) > 0):
        data = json.loads(data)
    print(data);
    schedule_id = data['finishId'];
    schedule = db.session.query(Schedule).filter(Schedule.id == schedule_id).first();
    if (session['user_id'] != schedule.user_id):
        colleague = db.session.query(Colleague).filter(
            and_(Colleague.user_id == schedule.user_id, Colleague.colleague_id == session['user_id'])).first();
        if (colleague.permission == 0):
            return ("无权限操作！");
    db.session.execute('update schedule set finished = :finished where id=:finishId',
                       {'finished': 1, 'finishId': schedule_id})
    db.session.commit();
    db.session.close();
    return ("待办完成！")

#日程/待办修改
@schedule.route("/schedule/schedule_update",methods=['GET','POST'])
def schedule_update():
    if login_judge() == False:
        return("尚未登陆")

    schedule = Schedule()
    schedule.id = request.form.get("schedule_id")
    schedule.title = request.form.get('title')
    schedule.value = request.form.get('value')
    schedule.repeat = request.form.get('repeat')
    schedule.alerm = request.form.get('alerm')
    schedule.repeat_cycle = request.form.get('repeat_cycle')
    schedule.user_id = session["user_id"]
    scheduleItem = db.session.query(Schedule).filter(Schedule.id == schedule.id).first();
    if (session['user_id'] != scheduleItem.user_id):
        colleague = db.session.query(Colleague).filter(
            and_(Colleague.user_id == session['user_id'], Colleague.colleague_id == scheduleItem.user_id)).first();
        if (colleague.permission == 1):
            db.session.close();
            return ("无权限操作！");
    db.session.merge(schedule)
    db.session.commit()
    db.session.close();
    return ("修改成功")

#日程/待办查看
@schedule.route("/schedule/schedule_info",methods=['GET','POST'])
def schedule_info():
    if login_judge() == False:
        return("尚未登陆")
    user_id = session["user_id"]
    schedule_list = db.session.query(Schedule).filter(Schedule.user_id==user_id).all()
    if schedule_list:
        schedule = schedule_list[0]
        # schedule_res = Schedule(schedule.id,schedule.user_id,schedule.title,schedule.value,schedule.repeat,schedule.repeat_cycle,schedule.alerm)
        # print(json.dumps(schedule_res, default=convert_to_builtin_type))
        db.session.close();
        return(schedule.title)
    else:
        db.session.close();
        return("尚无日程安排")

#待办删除
@schedule.route("/schedule/schedule_delete",methods=['GET','POST'])
def schedule_delete():
    if login_judge() == False:
        return("尚未登陆")
    schedule = Schedule()
    data = request.get_data("data")
    data = bytes.decode(data);

    if (len(data) > 0):
        data = json.loads(data)
    print(data);
    schedule= Schedule()
    schedule.schedule_id = data['deleteId'];
    schedule_list = db.session.query(Schedule).filter(Schedule.id==schedule.schedule_id).all()
    if schedule_list:
        schedule = schedule_list[0]
        # 如果当前ID和用户ID不一致，说明是好友在操作。判断权限
        if (session['user_id'] != schedule.user_id):
            colleague = db.session.query(Colleague).filter(
                and_(Colleague.user_id == session['user_id'], Colleague.colleague_id == schedule.user_id)).first();
            if (colleague.permission == 0):
                db.session.close();
                return ("无权限操作！");
        db.session.delete(schedule)
        db.session.commit()
        db.session.close();
        return("删除成功！")
    else:
        db.session.close();
        return("删除失败！")

#获取已完成待办
@schedule.route("/schedule/schedule_finish_list",methods=['GET','POST'])
def schedule_finish_list():
    if login_judge() == False:
        return("尚未登陆")
    schedule= Schedule()
    schedule.user_id=session["user_id"]
    schedule.finished=1
    query = db.session.query(Schedule).filter(Schedule.user_id==schedule.user_id)
    schedule_list = query.filter(Schedule.finished==schedule.finished).all()
    if schedule_list:
        db.session.close();
        return(len(schedule_list))
    else:
        db.session.close();
        return("尚无已完成的待办")

def login_judge():
    if session["user_id"]:
        if session["user_id"]!=0:
            return True
    else:
        return False

# def convert_to_dict(obj):
#     #'''把Object对象转换成Dict对象'''
#     dict = {}
#     dict.update(obj.__dict__)
#     return dict
# def convert_to_dicts(objs):
#     del (dict)
#     #'''把对象列表转换为字典列表'''
#     obj_arr = []
#     for o in objs:
#       #把Object对象转换成Dict对象
#       dict = {}
#       dict.update(o.__dict__)
#       obj_arr.append(dict)
#     return obj_arr
# def class_to_dict(obj):
#     #'''把对象(支持单个对象、list、set)转换成字典'''
#     is_list = obj.__class__ == [].__class__
#     is_set = obj.__class__ == set().__class__
#     if is_list or is_set:
#         obj_arr = []
#         for o in obj:
#             #把Object对象转换成Dict对象
#             dict = {}
#             dict.update(o.__dict__)
#             obj_arr.append(dict)
#         return obj_arr
#     else:
#         dict = {}
#         dict.update(obj.__dict__)
#         return dict

# def convert_to_builtin_type(obj):
#     print('default(', repr(obj), ')')
#     # Convert objects to a dictionary of their representation
#     d = { '__class__':obj.__class__.__name__,
#           '__module__':obj.__module__,
#         }
#     d.update(obj.__dict__)
#     return d